package com.jtech.together.view.weight;

import android.Manifest;
import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.common.Constants;
import com.jtech.together.util.RecordAudio;
import com.jtech.together.util.Util;
import com.jtech.together.view.weight.siriwave.WaveformView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.codetail.animation.ViewAnimationUtils;

/**
 * 录音键盘
 * Created by wuxubaiyang on 2017/5/16.
 */

public class RecordKeyboard extends CardView implements RecordAudio.OnRecordAudioListener {
    @Bind(R.id.imageview_record_keyboard_background)
    ImageView imageViewBackground;
    @Bind(R.id.imageview_record_keyboard_wrong)
    ImageView imageViewWrong;
    @Bind(R.id.imagebutton_record_keyboard_mic)
    ImageButton imageButtonMic;
    @Bind(R.id.textview_record_keyboard_time)
    TextView textViewTime;
    @Bind(R.id.textview_record_keyboard_info)
    TextView textViewInfo;
    @Bind(R.id.waveview_record_keyboard)
    WaveformView waveformView;

    private OnRecordKeyboardListener onRecordKeyboardListener;
    private long animationDuration = 260;
    private int transparentColor = android.R.color.transparent;
    private int defaultColor = R.color.white;
    private int accentColor = R.color.theme_color_primary_trans;
    private int wrongColor = R.color.red_warning;
    private RecordAudio recordAudio;

    public RecordKeyboard(Context context) {
        this(context, null);
    }

    public RecordKeyboard(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecordKeyboard(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化视图
        init();
    }

    /**
     * 初始化视图
     */
    private void init() {
        //实例化视图
        View contentView = LayoutInflater.from(getContext())
                .inflate(R.layout.view_record_keyboard, this, false);
        //绑定视图
        ButterKnife.bind(this, contentView);
        //添加视图
        addView(contentView);
        //设置卡片
        this.setCardBackgroundColor(Color.WHITE);
        //设置录音按钮的触摸事
        imageButtonMic.setOnTouchListener(new OnMicTouchListener());
        //实例化录音方法
        recordAudio = new RecordAudio(new File(getContext().getCacheDir() + "/" + Constants.CACHE_NAME));
        //设置录音监听
        recordAudio.setOnRecordAudioListener(this);
    }

    /**
     * 设置录音键盘监听
     *
     * @param onRecordKeyboardListener
     */
    public void setOnRecordKeyboardListener(OnRecordKeyboardListener onRecordKeyboardListener) {
        this.onRecordKeyboardListener = onRecordKeyboardListener;
    }

    /**
     * 重置
     */
    private void reset() {
        imageViewWrong.setImageResource(transparentColor);
        imageViewBackground.setImageResource(defaultColor);
        textViewInfo.setText("手指上滑,取消发送");
        textViewTime.setText("00:00:00");
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (null != onRecordKeyboardListener) {
            onRecordKeyboardListener.onRecordVisibilityChange(visibility == VISIBLE);
        }
    }

    /**
     * 显示背景
     */
    private void showBackground() {
        imageViewBackground.setImageResource(accentColor);
        // get the center for the clipping circle
        int cx = (imageViewBackground.getLeft() + imageViewBackground.getRight()) / 2;
        int cy = (imageViewBackground.getTop() + imageViewBackground.getBottom()) / 2;
        // get the final radius for the clipping circle
        int dx = Math.max(cx, imageViewBackground.getWidth() - cx);
        int dy = Math.max(cy, imageViewBackground.getHeight() - cy);
        float finalRadius = (float) Math.hypot(dx, dy);
        // Android native animator
        Animator animator = ViewAnimationUtils
                .createCircularReveal(imageViewBackground, cx, cy, 0, finalRadius);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setDuration(animationDuration);
        animator.start();
    }

    /**
     * 显示错误的背景
     */
    private void showWrongBackground() {
        imageViewWrong.setImageResource(wrongColor);
        // get the center for the clipping circle
        int cx = (imageViewWrong.getLeft() + imageViewWrong.getRight()) / 2;
        int cy = (imageViewWrong.getTop() + imageViewWrong.getBottom()) / 2;
        // get the final radius for the clipping circle
        int dx = Math.max(cx, imageViewWrong.getWidth() - cx);
        int dy = Math.max(cy, imageViewWrong.getHeight() - cy);
        float finalRadius = (float) Math.hypot(dx, dy);
        // Android native animator
        Animator animator = ViewAnimationUtils
                .createCircularReveal(imageViewWrong, cx, cy, 0, finalRadius);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setDuration(animationDuration);
        animator.start();
    }

    /**
     * 隐藏错误背景
     */
    private void hideWrongBackground() {
        // get the center for the clipping circle
        int cx = (imageViewWrong.getLeft() + imageViewWrong.getRight()) / 2;
        int cy = (imageViewWrong.getTop() + imageViewWrong.getBottom()) / 2;
        // get the final radius for the clipping circle
        int dx = Math.max(cx, imageViewWrong.getWidth() - cx);
        int dy = Math.max(cy, imageViewWrong.getHeight() - cy);
        float finalRadius = (float) Math.hypot(dx, dy);
        // Android native animator
        Animator animator = ViewAnimationUtils
                .createCircularReveal(imageViewWrong, cx, cy, finalRadius, 0);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                imageViewWrong.setImageResource(transparentColor);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        animator.setDuration(animationDuration);
        animator.start();
    }

    @Override
    public void onUpdate(float amplitude, long time) {
        //更新声音波纹
        waveformView.updateAmplitude(amplitude);
        //更新录音时间
        textViewTime.setText(Util.formatMediaLength(time));
    }

    @Override
    public void onStop(File audioFile) {
        if (null != onRecordKeyboardListener) {
            onRecordKeyboardListener.recordSuccess(audioFile);
        }
    }

    @Override
    public void onError() {
        if (null != onRecordKeyboardListener) {
            onRecordKeyboardListener.recordFail("已取消录音");
        }
    }

    /**
     * 获取权限
     */
    public void setupPermission(Activity activity) {
        Dexter.withActivity(activity)
                .withPermission(Manifest.permission.RECORD_AUDIO)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        recordAudio.prepare();
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        if (null != onRecordKeyboardListener) {
                            onRecordKeyboardListener.recordFail("无法获取权限");
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();
    }

    /**
     * 麦克风的触摸事件
     */
    private class OnMicTouchListener implements OnTouchListener {
        private int viewWidth, viewHeight;
        private int onceFlag = 1;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (viewWidth == 0 || viewHeight == 0) {
                viewWidth = v.getWidth();
                viewHeight = v.getHeight();
            }
            boolean flag = true;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN://按下
                    if (recordAudio.prepare()) {
                        //显示背景
                        showBackground();
                        //开始录音
                        recordAudio.startRecord();
                    } else {
                        if (null != onRecordKeyboardListener) {
                            onRecordKeyboardListener.recordFail("初始化失败");
                        }
                        reset();
                    }
                    break;
                case MotionEvent.ACTION_UP://抬起
                    if (onceFlag == 1) {
                        recordAudio.stopRecord();
                    } else {
                        recordAudio.cancelRecord();
                        if (null != onRecordKeyboardListener) {
                            onRecordKeyboardListener.recordFail("已取消录音");
                        }
                    }
                    //重置状态
                    reset();
                    break;
                case MotionEvent.ACTION_MOVE://移动
                    if (isInRange(event)) {
                        if (onceFlag != 1) {
                            onceFlag = 1;
                            textViewInfo.setText("手指上滑,取消发送");
                            hideWrongBackground();
                        }
                    } else {
                        if (onceFlag != 2) {
                            onceFlag = 2;
                            textViewInfo.setText("松开手指,取消发送");
                            showWrongBackground();
                        }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL://取消
                    recordAudio.cancelRecord();
                    if (null != onRecordKeyboardListener) {
                        onRecordKeyboardListener.recordFail("操作取消");
                    }
                    //重置状态
                    reset();
                    break;
                default:
                    flag = false;
                    break;
            }
            return flag;
        }

        /**
         * 判断当前是否是否在范围内
         *
         * @param event
         * @return
         */
        private boolean isInRange(MotionEvent event) {
            if (viewWidth != 0 && viewHeight != 0) {
                float x = event.getX();
                float y = event.getY();
                if (x > 0 && y > 0) {
                    if (x < viewWidth && y < viewHeight) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 录音键盘监听
     */
    public interface OnRecordKeyboardListener {
        void recordSuccess(File file);

        void recordFail(String error);

        void onRecordVisibilityChange(boolean isVisibility);
    }
}